<template>
  <div class="merchant-order-list">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
            <el-option
              v-for="(label, value) in orderStatusMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusType(row.status)">
              {{ orderStatusMap[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row.id)"
            >
              查看详情
            </el-button>
            <el-button
              v-if="row.status === 1"
              link
              type="success"
              @click="handleShip(row)"
            >
              发货
            </el-button>
            <el-button
              v-if="row.status === 5"
              link
              type="warning"
              @click="handleRefund(row)"
            >
              退款处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="快递公司" prop="deliveryCompany">
          <el-select
            v-model="shipForm.deliveryCompany"
            placeholder="请选择快递公司"
            style="width: 100%"
          >
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="deliveryNo">
          <el-input v-model="shipForm.deliveryNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip" :loading="shipSubmitting">
          确认发货
        </el-button>
      </template>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款处理"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <span>¥{{ currentOrder?.refundAmount }}</span>
        </el-form-item>
        <el-form-item label="退款原因">
          <span>{{ currentOrder?.refundReason }}</span>
        </el-form-item>
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="refundForm.status">
            <el-radio :label="1">同意退款</el-radio>
            <el-radio :label="0">拒绝退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="refundForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMerchantOrders, shipOrder, auditRefund } from '@/api/order'

const router = useRouter()

// 订单状态映射
const orderStatusMap = {
  0: '待支付',
  1: '已支付',
  2: '已发货',
  3: '已完成',
  4: '已取消',
  5: '退款中',
  6: '已退款'
}

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  const statusTypeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'success',
    4: 'danger',
    5: 'warning',
    6: 'info'
  }
  return statusTypeMap[status] || 'info'
}

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: null
})

// 数据相关
const loading = ref(false)
const orderList = ref([])
const total = ref(0)

// 获取订单列表
const getList = async () => {
  try {
    loading.value = true
    const response = await getMerchantOrders(queryParams)
    if (response.code === 200) {
      orderList.value = response.data.records
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.status = null
  handleQuery()
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 查看详情
const handleDetail = (id) => {
  router.push(`/merchant/order/detail/${id}`)
}

// 发货相关
const shipDialogVisible = ref(false)
const shipSubmitting = ref(false)
const currentOrder = ref(null)
const shipForm = reactive({
  deliveryCompany: '',
  deliveryNo: ''
})

const shipRules = {
  deliveryCompany: [
    { required: true, message: '请选择快递公司', trigger: 'change' }
  ],
  deliveryNo: [
    { required: true, message: '请输入快递单号', trigger: 'blur' }
  ]
}

const handleShip = (row) => {
  currentOrder.value = row
  shipDialogVisible.value = true
  shipForm.deliveryCompany = ''
  shipForm.deliveryNo = ''
}

const confirmShip = async () => {
  if (!currentOrder.value) return
  
  try {
    shipSubmitting.value = true
    const response = await shipOrder(
      currentOrder.value.id,
      shipForm.deliveryCompany,
      shipForm.deliveryNo
    )
    if (response.code === 200) {
      ElMessage.success('发货成功')
      shipDialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('发货失败:', error)
    ElMessage.error('发货失败')
  } finally {
    shipSubmitting.value = false
  }
}

// 退款处理相关
const refundDialogVisible = ref(false)
const refundSubmitting = ref(false)
const refundForm = reactive({
  orderId: null,
  status: 1,
  remark: ''
})

const refundRules = {
  status: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入处理备注', trigger: 'blur' }
  ]
}

const handleRefund = (row) => {
  currentOrder.value = row
  refundDialogVisible.value = true
  refundForm.orderId = row.id
  refundForm.status = 1
  refundForm.remark = ''
}

const confirmRefund = async () => {
  try {
    refundSubmitting.value = true
    const response = await auditRefund(refundForm)
    if (response.code === 200) {
      ElMessage.success('处理成功')
      refundDialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error('处理失败:', error)
    ElMessage.error('处理失败')
  } finally {
    refundSubmitting.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.merchant-order-list {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 